<?php

namespace app\admin\controller\template;

use app\admin\model\User;
use app\common\controller\Backend;
use think\Db;

/**
 * 模板订单管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\template\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\template\Order;
        $statusList = [1 => '核算模板', 2 => '核算服务'];
        $this->view->assign("statusList", $statusList);
        $payList = [0 => '待付款', 1 => '已完成', 2 => '已取消'];
        $this->view->assign("payList", $payList);
    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            $userNameList = [];
            $this->model->with(['user' => function ($query) {
                $query->field('id,nickname');
            }])->field('user_id')->select()->each(function ($item) use (&$userNameList) {
                if ($item->user) {
                    $userNameList[$item['user_id']] = $item->user->nickname;
                }
            });
            $this->assignconfig('userNameList', $userNameList);
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $data = $this->model->where($where)
            ->field(['id', 'order_sn', 'user_id', 'price', 'pay_state', 'pay_state pay_state_id', 'paytime', 'createtime', 'updatetime', 'author_commission_ratio', 'type', 'type type_id'])
            ->order($sort, $order)
            ->paginate($limit)
            ->each(function ($item) {
                if ($item->pay_state_id == 1) {
                    $item->username = User::where('id', $item->user_id)->value('nickname');
                    if ($item->type_id == 1) {
                        $item->service_fee = $item->price - $item->author_commission_ratio;
                    } else {
                        $service_fee = 0;
                        Db::name('order_template')
                            ->where('order_id', $item->id)
                            ->field(['order_id', 'service_fee'])
                            ->union(function ($query) use ($item) {
                                $query->table('zt_order_factor')
                                    ->where('order_id', $item->id)
                                    ->field(['order_id', 'platform_service_fee service_fee']);
                            })
                            ->select()
                            ->each(function ($item) use (&$service_fee) {
                                $service_fee += $item['service_fee'];
                            });
                        $item->service_fee = $service_fee;
                    }
                }
                unset($item->author_commission_ratio, $item->pay_state_id);
            });

        $result = ['total' => $data->total(), 'rows' => $data->items()];
        return json($result);
    }

    public function detail($ids)
    {
        $row = $this->model->where('id', $ids)->field(['*', 'type type_id'])->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row->username = User::where('id', $row->user_id)->value('nickname');
        $row->template_name = \app\admin\model\template\Template::where('id', $row->template_id)->value('name');
//        $row->createtime = date('Y年m月d日 H时i分s秒', $row->createtime);
//        $row->updatetime = !$row->updatetime ? null : date('Y年m月d日 H时i分s秒', $row->updatetime);
        if ($row->type_id == 2) {
            $factors = $row->factors;
            // 碳排放因子数据库
            foreach ($factors as &$factor) {
                $factor['username'] = User::where('id', $factor['user_id'])->value('nickname');
            }
            $row->factorList = $factors;
            unset($factors);
            // 模板核算分成
            $row->templates = Db::name('order_template')->field(['template_id', 'price', 'from_user'])->where('order_id', $row->id)->select()->each(function ($item) {
                $item['username'] = User::where('id', $item['from_user'])->value('nickname');
                $template = \app\admin\model\template\Template::where('id', $item['template_id'])->field(['sn', 'name'])->find()->toArray();
                $item = array_merge($item, $template);
                unset($template);
                return $item;
            })->toArray();
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

}
